<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"> 
    <style type="text/css">
      html, body, { height: 100%; margin: 0; padding: 0;}
      #map-canvas {
        width: 95%;
        height: 550px;
        margin: 10px;
        float: left;
      }
      #time {
        height: 15px;
        width: 100%;
        margin-left: 10px;
      }
      #time-label {
        width: 50px;
        margin-left: 10px;
      }
      #legend {
        width: 95%;
      }
    </style>
    

    <script type="text/javascript" src="js/jquery.min.js"></script>
    <link rel="stylesheet" href="css/jquery-ui.min.css">
    <script src="js/jquery-ui.min.js"></script>

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=visualization&key=AIzaSyARde3l38fdZyf5nwQWc-iPVgtHRb6NlwM"></script>
    <script type="text/javascript">
      var map;
      var json_data = [];
      var heatmap;
      var marker;
      var matched_idx;

      function process_json_data(data) {
        json_data = data[0]? data[0] : data;
        map = initialize_map(data.center);

        map.addListener('zoom_changed', function() {
          show_heatmap(map.zoom);
        });

        $("#time").slider({
          orientation: 'horizontal',
          value: 0,
          min: 0,
          max: json_data.points.length - 1,
          step: 1,
          animate: 'fast',
          slide: function( event, ui ) {
            update_position(ui.value);
          }
        });

        $("#scan_title").html("Scanning results for <code>'" + data.title + "'</code>");
        show_heatmap(map.zoom);
        update_position(0);
      }


      $(document).ready(function () {
        var queryDict = {};
        location.search.substr(1).split("&").forEach(function(item) {
          queryDict[item.split("=")[0]] = item.split("=")[1];
        });

        if (queryDict['f']) {
          $.getJSON('/heatmap/show/' + queryDict['f'], function (data) {
            process_json_data(data);
          });
        } else { // show overview map
          map = initialize_map({lat: 30, lon: 0}, 2);
          var scan_layer = new google.maps.KmlLayer({
            url: 'http://www.tautology2.net/heatmap.kml',
            map: map
          });
          console.log(scan_layer);
        }
          
        $(':button').click(function(){
          var formData = new FormData($('form')[0]);
          $.ajax({
              url: '/heatmap/create_heatmap.json',  //Server script to process data
              type: 'POST',
              xhr: function() {  // Custom XMLHttpRequest
                  var myXhr = $.ajaxSettings.xhr();
                  return myXhr;
              },
              success: process_json_data,
              // error: errorHandler,
              // Form data
              data: formData,
              //Options to tell jQuery not to process data or worry about content-type.
              cache: false,
              contentType: false,
              processData: false
          });
        });
      });


      function update_position(idx) {
        show_marker(idx);
        $('#legend-time').text((new Date(1000*json_data.points[idx].ts)).toLocaleString());
      }


      function initialize_map(center, zoom) {
        var zoom = (typeof zoom !== 'undefined')? zoom : 13;
        var mapOptions = {
          center: {lat: center.lat, lng: center.lon},
          zoom: zoom,
          scaleControl: true,
          panControl: false,
          zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.RIGHT_CENTER
          },
          mapTypeId: google.maps.MapTypeId.HYBRID,
        };
        return new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      }


      function zoom2intensity(zoom) {
        default_scale = 1000;

        var scale = {
          11: 2000,
          12: 1000,
          13: 500,
          14: 240,
          15: 125,
          16: 100
        };

        zooms = Object.keys(scale).sort();
        if (scale[zoom]) { return scale[zoom]; }
        if (zoom < zooms[0]) { return scale[zooms[0]]; }
        if (zoom > zooms[zooms.length - 1]) { return scale[zooms.pop()]; }
        return default_scale;
      }


      function show_heatmap(zoom_level) {
        var heatMapData = [];
        // console.log('zooming to ', zoom_level);

        $.each(json_data.points, function(idx, point) {
          heatMapData.push({location: new google.maps.LatLng(point.lat, point.lon), weight: point.spectrum });
        });

        if (heatmap) { heatmap.setMap(null) }
        var maxintens = zoom2intensity(zoom_level);
        heatmap = new google.maps.visualization.HeatmapLayer({
          data: heatMapData,
          maxIntensity: zoom2intensity(zoom_level),
          radius: 20,
        });
        heatmap.setMap(map);
      }


      function show_marker(idx) {
        if (marker) {marker.setMap(null);}

        var lat = json_data.points[idx].lat;
        var lon = json_data.points[idx].lon;

        marker = new google.maps.Marker({
          position: new google.maps.LatLng(lat, lon),
          map: map,
          title: lat + ', ' + lon
        });
      }
    </script>
  </head>
  <body>
    <h3 style="margin-left: 90px;" id="scan_title">Scanning results</h3>
    <div id="map-canvas" class="map"></div>
    <table id="legend">
      <tr>
        <td colspan="2">
          <div id="time"></div>
          <div id="time-label"></div>
        </td>
      </tr>
      <tr>
        <td><b>Time:</b></td><td id="legend-time"></td>
      </tr>
    </table>

    <h3>Uploaded files</h3>
    <ol>
      <% if false %>
      <% @rfs_list.each do |file_name| %>
        <li><a href="/heatmap/single_band_index.html?f=<%= URI.escape(file_name) %>"><%= file_name %></a></li>
      <% end %>
      <% end %>
    </ol>

    <form enctype="multipart/form-data">
      <input name="file" type="file" />
      <input type="button" value="Upload" />
    </form>
    <div>
      <br />
      <br />
      This is the RF heatmap builder. If you want to plot your own heatmap, do the following:
      <br />
      <ol>
        <li> Attach and configure the RTL-SDR dongle and GPS receiver to your computer</li>
        <li> Record scan in .rfs format using <a href="http://eartoearoak.com/software/rtlsdr-scanner">RTLSDR Scanner</a>.</li>
        <li> Upload scan to heatmap builder using form on this page</li>
      </ol>
      <br />
      See also: <a href="/heatmap/">GSM heatmap</a>, <a href="https://www.reddit.com/r/RTLSDR/comments/2hbjyt/gsm_heatmap_using_rtlsdr/">Reddit discussion</a>, <a href="https://github.com/ati/heatmap">GitHub repo</a>.
  </body>
</html>
